package csc.fresher.spring.dao;

import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;

import csc.fresher.spring.model.User;

public class UserDAOImpl implements UserDAO {

	private DataSource dataSource;
	private JdbcTemplate jdbcTemplate;

	@Override
	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
		this.jdbcTemplate = new JdbcTemplate(dataSource);

	}

	@Override
	public void insertUser(String username, String password, String idcard,
			String firstname, String lastname, String phone, String email) {
		String SQL = "insert into User(username, password, idcard, firstname, lastname, phone, email)"
				+ " values (?, ?, ? , ?, ?, ?, ?)";
		jdbcTemplate.update(SQL, username, password, idcard, firstname,
				lastname, phone, email);

	}

	@Override
	public User getUser(String username) {
		// TODO Auto-generated method stub
		String SQL = "select * from user where username = ?";
		User u = jdbcTemplate.queryForObject(SQL, new Object[] { username },
				new UserMapper());
		return u;
	}

	@Override
	public List<User> listUser() {
		String SQL = "select * from user";
		List<User> list = jdbcTemplate.query(SQL, new UserMapper());
		return list;
	}

	@Override
	public void deleteUser(String username) {
		String SQL = "delete from user where username = ?";
		jdbcTemplate.update(SQL, username);

	}

	@Override
	public void updateUser(String username) {
		// TODO Auto-generated method stub

	}

	@Override
	public void insertTrackUser(String username) {
		String SQL = "insert into trackuser(username) values (?)";
		jdbcTemplate.update(SQL, username);

	}

	@Override
	public void deleteUserRole(String username) {
		String SQL = "delete from user_role where username = ?";
		jdbcTemplate.update(SQL, username);

	}

	@Override
	public void insertUserRole(String username) {
		String SQL = "insert into user_role(username, role) values (?, ?)";
		if (username.equals("admin")) {
			jdbcTemplate.update(SQL, username, "ROLE_ADMIN");
		} else {
			jdbcTemplate.update(SQL, username, "ROLE_USER");
		}

	}

	@Override
	public boolean checkUser(String username) {
		String SQL = "select count(*) from user where username = ?";
		int number = jdbcTemplate.queryForInt(SQL, username);
		if (number == 0) {
			return false;
		}
		return true;
	}

}
